/**
 * 
 */
package es.ucm.fdi.xtremeaudio.vista;

import java.awt.Container;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import javax.swing.JComponent;
import javax.swing.JFrame;

/**
 * @author ucm-is-grupo7-2011
 * 
 */
public class MoverPanelListener implements MouseListener, MouseMotionListener {

	JComponent target;
	Point start_drag;
	Point start_loc;

	public MoverPanelListener(JComponent target) {
		this.target = target;
	}

	public static JFrame getFrame(Container target) {
		if (target instanceof JFrame) {
			return (JFrame) target;
		}
		return getFrame(target.getParent());
	}

	Point getScreenLocation(MouseEvent e) {
		Point cursor = e.getPoint();
		Point target_location = target.getLocationOnScreen();
		return new Point((int) (target_location.getX() + cursor.getX()),
						 (int) (target_location.getY() + cursor.getY()));
	}
	
	@Override
	public void mouseDragged(MouseEvent e) {
		Point current = getScreenLocation(e);
	    Point offset = new Point((int) current.getX() - (int) start_drag.getX(),
	    						 (int) current.getY() - (int) start_drag.getY());
	    JFrame frame = getFrame(target);
	    Point new_location = new Point((int) (start_loc.getX() + offset.getX()),
	    							   (int) (start_loc.getY() + offset.getY()));
	    frame.setLocation(new_location);
	}

	@Override
	public void mousePressed(MouseEvent e) {
	    start_drag = getScreenLocation(e);
	    start_loc = getFrame(target).getLocation();		
	}
	
	@Override
	public void mouseClicked(MouseEvent e) {}

	@Override
	public void mouseEntered(MouseEvent e) {}

	@Override
	public void mouseExited(MouseEvent e) {}
	
	@Override
	public void mouseReleased(MouseEvent e) {}	

	@Override
	public void mouseMoved(MouseEvent e) {}

}